package controllers

import (
	"beego/models"
	"beego/service"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/mitchellh/mapstructure"
	"io/ioutil"
	"net/http"
	"reflect"
	"strings"
	"time"
)

type ConvertController struct {
	beego.Controller
}

func init() {
	orm.RegisterModel(new(models.NewsSearch))
}

/**
 * @Title JsonToMap
 * @Description json转Map
 */

func (c *ConvertController) JsonToMap() {
	//Json转Map
	var r service.Request
	r.Req = `{
		"code": 0,
		"info": "Success",
		"data": {
			"location": {
				"lng": 120.322,
				"lat": 40.9834
			},
			"address": "辽宁省葫芦岛市连山区"
		},
		"list": [{
			"name": "beJson",
			"title": "始于2011"
		},{
			"name": "golang",
			"title": "性价比最优选"
		}]
	}`
	// 1.方法一
	//var req2map map[string]interface{}
	//err := json.Unmarshal([]byte(r.Req),&req2map)

	// 2.方法二
	req2map, err := r.Json2map()
	if err != nil {
		fmt.Println(err)
	}
	c.Data["json"] = req2map
	c.ServeJSON() //对json进行序列化输出
	c.StopRun()
}

type UserInfoVo struct {
	Id       int         `json:"id"`
	UserName string      `json:"user_name"`
	Address  []AddressVo `json:"address"`
}

type AddressVo struct {
	Address string `json:"address"`
}

/**
 * @Title Handle
 * @Description 结构体转Map
 */

func (c *ConvertController) StructToMap() {
	User := UserInfoVo{
		Id:       1,
		UserName: "酒窝猪",
		Address: []AddressVo{
			{Address: "湖南"},
			{Address: "北京"},
		},
	}

	var resultMap interface{}
	before := time.Now()
	jsonMarshal, _ := json.Marshal(User)
	err := json.Unmarshal(jsonMarshal, &resultMap)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(time.Since(before))
	fmt.Printf("%+v", resultMap)
	c.Data["json"] = resultMap
	c.ServeJSON() //对json进行序列化输出
	c.StopRun()
}

/**
 * @Title Handle
 * @Description 打印文本
 */

func (c *ConvertController) Handle() {
	Id, _ := c.GetInt("id", 2)
	returnData := make(map[string]int)
	returnData["Id"] = Id
	if c.IsAjax() {
		c.Data["yaml"] = 222
	} else {
		c.Data["yaml"] = 111
	}
	c.ServeYAML()
	c.StopRun()
}

/**
 * @Title CustomParse
 * @Description 将JSON字符转为MAP结构
 */

func (c *ConvertController) SearchGet() {
	// JSON数据处理
	ret := service.ReturnMsg{
		Code: 200, Msg: "Success",
	}
	Id := c.GetString("id", "")
	fmt.Println("ID:", Id)
	if Id == "" {
		ret.Code, ret.Msg = 10001, "Id不能为空"
	}
	NewsSearch := models.NewsSearch{}
	NewsSearch.Id = Id

	OutMysql := orm.NewOrm()
	err := OutMysql.Read(&NewsSearch)

	if err == orm.ErrNoRows {
		ret.Code = 10002
		ret.Msg = "Data does not exist." //空数据
		c.Data["json"] = ret
		c.ServeJSON() // 对json进行序列化输出
		c.StopRun()
	}

	mapObj := make(map[string]interface{})
	JsonStr, _ := json.Marshal(NewsSearch)
	_ = json.Unmarshal([]byte(JsonStr), &mapObj)
	delete(mapObj, "Params")

	tmpMap := make(map[string]interface{})
	tmpStr := NewsSearch.Params
	_ = json.Unmarshal([]byte(tmpStr), &tmpMap)
	mapObj["Params"] = tmpMap
	ret.Data = mapObj
	c.Data["json"] = ret
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}

/**
 * @Title DataParse
 * @Description 将字符串转slice
 */

func (c *ConvertController) DataParse() {
	content := "hello 中国"
	content2 := []rune(content)
	var SliceData []string
	for i := 0; i < len(content2); i++ {
		SliceData = append(SliceData, string(content2[i]))
	}
	fmt.Println(SliceData)
	c.Data["json"] = SliceData
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}

/**
 * @Title CustomParse
 * @Description 将字符串按照指定字符切割成slice
 */

func (c *ConvertController) CustomParse() {
	content := "hello 中国"
	sep := " "
	SliceData := strings.Split(content, sep)
	c.Data["json"] = SliceData
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}

/**
 * 采集JSON接口
 */
func (c *ConvertController) BaiduNewsGet() {
	// JSON数据处理
	ret := service.ReturnMsg{
		Code: 200, Msg: "Success",
	}
	// 当前时间，拼接请求地址
	now := time.Now()
	microTime := now.UnixNano() / 1e6
	var Method = c.Ctx.Input.Method()
	var TmpUrl string
	var Reponse *http.Response
	var err error
	if Method == "GET" {
		TmpUrl = fmt.Sprintf("https://news.baidu.com/widget?id=LocalNews&loc=2587&ajax=json&t=%d", microTime)
		Reponse, err = http.Get(TmpUrl)
	} else {
		Type, _ := c.GetInt("type", 1)
		if Type == 1 {
			// POST form=data
			TmpUrl = "http://tp6.hzshare.com/index/rangeData"
			var ReqestParam = strings.NewReader("id=6")
			Reponse, err = http.Post(TmpUrl, "application/x-www-form-urlencoded", ReqestParam)
		} else {
			// POST json
			TmpUrl = "http://tp6.hzshare.com/index/rangeJson"
			JsonData := make(map[string]interface{})
			JsonData["id"] = "5"
			ReqestParam, _ := json.Marshal(JsonData)
			reader := bytes.NewReader(ReqestParam)
			Reponse, err = http.Post(TmpUrl, "application/json; charset=utf-8", reader)
		}
	}
	if err != nil {
		fmt.Printf("Reponse Failed, Err:%v\n", err)
		ret.Code, ret.Msg = 0, err.Error()
		c.Data["json"] = ret
	} else {
		defer Reponse.Body.Close()
		body, err := ioutil.ReadAll(Reponse.Body)
		if err != nil {
			fmt.Printf("read from resp.Body failed, err:%v\n", err)
			ret.Code, ret.Msg = 0, err.Error()
		} else {
			// 将数据转为JSON字符
			Req := string(body)
			PrintInfo := make(map[string]interface{})
			_ = json.Unmarshal([]byte(Req), &PrintInfo)

			// 获取Map对应键值类型，如果需要处理对应数据
			for _, value := range PrintInfo {
				_ = reflect.TypeOf(value)
			}
			// 判断Map是否存在指定key值
			if _, ok := PrintInfo["session"]; !ok {
				PrintInfo["Sess"] = "beeGo"
			}
			// 添加Map对应键
			PrintInfo["Url"], PrintInfo["Data"] = TmpUrl, PrintInfo["data"]
			// 删除Map对应键
			delete(PrintInfo, "data")
			ret.Data = PrintInfo
		}
		c.Data["json"] = ret
	}
	c.ServeJSON() // 对json进行序列化输出
	c.StopRun()
}
